import { command } from '@/ts/base';
import { ITarget } from '@/ts/core';
import { IModel } from '@/ts/core/chat/agent/aiModel';
import { Button, Card, Modal, Space, Table } from 'antd';
import React, { useEffect, useState } from 'react';

interface IProps {
  target: ITarget;
  id: string;
}

const ModelSetting = (props: IProps) => {
  const [models, setModels] = useState(props.target.modelManager.models);
  useEffect(() => {
    const id = props.target.modelManager.subscribe(async () => {
      await props.target.modelManager.loadContent();
      setModels([...props.target.modelManager.registerModels]);
    });
    return () => {
      props.target.modelManager.unsubscribe(id);
    };
  }, []);
  return (
    <Card
      title="模型设置"
      id={props.id}
      extra={
        <>
          {props.target.hasDataAuth() && (
            <Button
              onClick={() => {
                command.emitter('executor', 'newModel', props.target.modelManager);
              }}>
              添加模型
            </Button>
          )}
        </>
      }>
      <Table<IModel>
        dataSource={models}
        columns={[
          { title: '协议', dataIndex: 'protocol' },
          { title: '模型名称', dataIndex: 'code' },
          { title: '备注', dataIndex: 'remark' },
          {
            title: '操作',
            dataIndex: 'actions',
            render: (_, record) => {
              return (
                <Space size={16}>
                  <a
                    onClick={() => {
                      command.emitter('executor', 'updateModel', record);
                    }}>
                    修改
                  </a>
                  <a
                    onClick={() => {
                      command.emitter('executor', 'copyModel', record);
                    }}>
                    复制
                  </a>
                  <a
                    onClick={() => {
                      Modal.confirm({
                        title: '删除模型',
                        content: '确定要删除该模型吗？',
                        okText: '确定',
                        cancelText: '取消',
                        onOk: async () => {
                          await record.delete();
                        },
                      });
                    }}>
                    删除
                  </a>
                </Space>
              );
            },
          },
        ]}
      />
    </Card>
  );
};

export default ModelSetting;
